import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber,Switch, TreeSelect,Upload,Table, Button, Icon, Select, Radio, message } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import React, { useState,useEffect } from 'react';

import CryptoJS from 'crypto-js';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';
import DataLang from './DataLang';
import styles from '../index.less';
import { InputSizes } from 'antd/es/input/Input';
// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common,handleName,nameList, isUpdate,dataFormValues ,selectType} = props;
    const [dataLangModalVisible, handleDataModalVisible] = useState<boolean>(false);
  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');
  // const [nameList, handleName] = useState([]);
  const imgList: any = [];
  const dtImgList: any = [];
  const rankChangeList: any = [];
  const [nameListLang, setnameList] = useState<any>([]);
  const handleNameList = (val)=>{
    setnameList(val)
} 
  const handleChange = (value: any, option: any) => {
    let obj = {};
    let isSelect = true;
    option.map((item: any, index: any) => {
      if (value == item.key) {
        obj = item;
      }
    })
    let len = nameList.length;
    let coupon = [];
    console.log(coupon, 122)
    nameList.map((item: any, index: any) => {
      if (value == item.lang_code) {
        isSelect = false;
      }
      coupon.push({ lang_code: item.lang_code, lang_content:item.lang_content });
    })
    if (isSelect) {
      coupon.push({ lang_code: value, lang_content:'' });
    }
    console.log(coupon, 332)
    handleName(coupon);
  }
//上传图片列表列
const columns = [
  {
    title: '标签',
    dataIndex: 'key',
  },
  {
    title: '语言描述',
    dataIndex: 'text',
  },
  {
    title: '内容',
    dataIndex: 'lang_content',
    // render: (text, record, index) => (
    //   <Input value={record.lang_content} onChange={e => { rankChange(record, e.target.value, index) }} />
    // )
  },
];
  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.icon_file_id   = picture[0].file_id
        fieldsValue.icon_file_url  = picture[0].file_url
      }
      // 如果是更新
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      // if(isUpdate){
      //   fieldsValue.name = JSON.stringify(dataFormValues.nameArr);
      // }else{
      //   fieldsValue.name = JSON.stringify(nameList);
      // }
      var arr = []
      nameList.map(item =>{
        var obj = {
           lang_code:item.key,
           lang_text:item.text,
           lang_content:item.lang_content,
        }
        arr.push(obj)
      })
      console.log(arr,434)
      fieldsValue.name = JSON.stringify(arr);
      if(fieldsValue.scene){
        fieldsValue.scene = fieldsValue.scene.join(',');
      }
      if(fieldsValue.member_roles){
        fieldsValue.member_roles = fieldsValue.member_roles.join(',')
      }
      console.log("submit fields ", fieldsValue)
      fieldsValue.type = selectType
      // 如果更新成功之后，重置表单
      handleSubmit(fieldsValue).then((success:any) => {
        console.log('handleSubmit then success is ', success)
        if(success){
          form.resetFields()
          setPicture([])
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    if(fileList.length>0 && fileList[0].response && fileList[0].response?.code != 0){
      message.error(fileList[0].response.message);
      return
    }
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.icon_file_url)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)
  function issetParam(param: any) {
    if (param === null || param === undefined) {
      return false
    }
    return true
  }
  function getTreeData(common: {}, fields) {
    let treeData = []
    if (issetParam(common[fields])) {
      treeData = common[fields]
      console.log(treeData)
    }
    // console.log('get tree data res', treeData)
    return treeData
  }
  // 表单提交
  const handleSubmitDataForm = (value:any) => {
    console.log(value,1356)
    handleName(value)
    handleDataModalVisible(false)
}
const buildSelectOption = (arr: any) => {
  // @ts-ignore
  return arr.map((d: any) => {
    if (d.disabled && d.disabled == true) {
      return undefined;
    } else if (d.name) {
      if (d.name != '用户'){
        return <Select.Option key={d.key} value={(d.key).toString()}>{d.name}</Select.Option>
      }  
    } else {
      return <Select.Option key={d.key} value={(d.key).toString()}>{d.text}</Select.Option>
    }
  })
}
  const treeData = getTreeData(common,'roleOption')
  const treeData1 = getTreeData(common,'sceneOption')
  const treeProps = {
    treeData: treeData,
    // onChange: this.handleCategoryChange,
    treeDefaultExpandAll: true,
    searchPlaceholder: '搜索值',
    style: { width: '100%' },
  }
  const treeProps1 = {
    treeData: treeData1,
    // onChange: this.handleCategoryChange,
    treeDefaultExpandAll: true,
    searchPlaceholder: '搜索值',
    style: { width: '100%' },
  }

  const userInfo = localStorage.getItem('user-login-info');
  let fresnsClient = eval("(" + userInfo + ")");
  const timestamp = new Date().getTime().toString().substr(0,10);
  var md5String = `appId=${fresnsClient?.app_id}&platform=${fresnsClient?.platform}&timestamp=${timestamp}&key=${fresnsClient?.app_secret}`;

  // 弹出框
  // @ts-ignore
  return <Modal
    destroyOnClose
    title={isUpdate?'编辑':'新增'}
    width={DataHelper.DEFAULT_MODAL_WIDTH}
    visible={dataModalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
  >
    {selectType == 6 ?(
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.belonging_to_the_group' })}>
      {form.getFieldDecorator('group_id', {
        initialValue: isUpdate ? dataFormValues.group_id?.toString() : '',
        //rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
      {common.groupOption && TsxHelper.buildSelectOption(common.groupOption)}
    </Select>)}
    </FormItem>
    ):null}
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.display_order' })}>
      {form.getFieldDecorator('rank_num', {
        initialValue: isUpdate ? dataFormValues.rank_num : 88,
       // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }} min={1}/>)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.associated_plug-in' })}>
      {form.getFieldDecorator('plugin_unikey', {
        initialValue: isUpdate ? dataFormValues.plugin_unikey?.toString() : '',
        //rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Select placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
      {common.plugOption && TsxHelper.buildSelectOption(common.plugOption)}
    </Select>)}
    </FormItem>
    <FormItem className={styles.input} labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.name' })}>
      {form.getFieldDecorator('lang', {
        initialValue:nameList && nameList.length>0 ? nameList[0].lang_content:'',
        //rules: [{ required: true, message: '请选择！', }],
      })(<Input readOnly unselectable="on"  onClick={() => { setnameList(nameList);handleDataModalVisible(true);}} />)}
    </FormItem>
    {/* <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.lang' })}>
      {form.getFieldDecorator('lang', {
        initialValue: isUpdate ? dataFormValues.lang?.toString() : undefined,
        //rules: [{ required: true, message: '请选择！', }],
      })(<Select onSelect={(e) => handleChange(e, common.multilingualoption)} placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
        {common.multilingualoption && TsxHelper.buildSelectOption(common.multilingualoption)}
      </Select>)}
    </FormItem> */}
    {/* <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.name' })}>
      <Table
        columns={columns}
        dataSource={nameList && nameList.length>0 ? nameList.slice(0,1):nameList}
        pagination={false}
      />
    </FormItem> */}
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.show_icon' })}>
      {form.getFieldDecorator('picture', {
        // initialValue: defaultPicture,
        // rules: [{required: true, message: '请上传图片'}],
      })(
        <Upload
          listType={'picture'}
          className={'upload-list-inline'}
          action="/api/admin/tweetfiles/upload"
          defaultFileList={isUpdate?defaultPicture:[]}
          beforeUpload={(file) => {
            console.log('before upload file type:', file.type)
            // todo: 这里可以对上传文件类型做限制
            return true;
          }}
          data={{ type: 'image' }}
          onRemove={() => setPicture([])}
          onChange={(changeObj) => setUploadFile(changeObj.fileList)}
          onPreview={() => handlePreviewModalVisible(true)}
          headers={{
            Authorization: `Bearer ${token}`,
            'platform': fresnsClient?.platform,
            'timestamp': timestamp,
            'appId': fresnsClient?.app_id,
            'sign':  CryptoJS.MD5(md5String).toString(),
          }}
        >
          {
            showUploadButton ? (
              <Button>
                <Icon type="upload"/> {formatMessage({ id: 'app.base.upload' })}
              </Button>
            ) : null
          }
        </Upload>
      )}
    </FormItem>
    {selectType == 3 ?(
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.number_of_applications' })}>
      {form.getFieldDecorator('editor_number', {
        initialValue: isUpdate ? dataFormValues.editor_number : '',
       // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<InputNumber placeholder={formatMessage({ id: 'app.base.please_input' })} style={{ width: '100%' }} min={1} max={10}/>)}
    </FormItem>
    ):null}

    {selectType == 5 ?(
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.application_scenarios' })}>
              {form.getFieldDecorator('scene', {
                initialValue: isUpdate ? dataFormValues.scene : [],
                // rules: [{ required: true, message: '请选择！', }],
              })(<Select mode="multiple" placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
              {common.sceneOption && TsxHelper.buildSelectOption(common.sceneOption)}
          </Select>)}
            </FormItem>
    ):null}
      {selectType == 3 ?(
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.application_scenarios' })}>
              {form.getFieldDecorator('scene', {
                initialValue: isUpdate ? dataFormValues.scene : [],
                // rules: [{ required: true, message: '请选择！', }],
              })(<Select mode="multiple" placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
              {common.sceneOption && buildSelectOption(common.sceneOption)}
          </Select>)}
            </FormItem>
    ):null}
    {selectType != 4 ?(<>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.custom_parameters' })}>
        {form.getFieldDecorator('parameter', {
          initialValue: isUpdate ? dataFormValues.parameter : '',
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
        })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
      </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.usage_rights' })}>
              {form.getFieldDecorator('member_roles', {
                initialValue: isUpdate ? dataFormValues.userRolesArr : [],
                // rules: [{ required: true, message: '请选择！', }],
              })(<Select mode="multiple" placeholder={formatMessage({ id: 'app.base.please_select' })} size={'default'} style={{ width: '100%' }}>
              {common.roleOption && TsxHelper.buildSelectOption(common.roleOption)}
          </Select>)}
            </FormItem>
            </>):null}
            {/* {selectType == 5 ?(
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.for_group_administrators' })}>
          {form.getFieldDecorator('is_group_admin', {
            initialValue: isUpdate ? dataFormValues.is_group_admin : 0,
            valuePropName: 'checked',
            // rules: [],
          })(<Switch  />)}
        </FormItem>):null} */}
            <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={formatMessage({ id: 'app.base.enabled_state' })}>
          {form.getFieldDecorator('is_enable', {
            initialValue: isUpdate ? dataFormValues.is_enable : 0,
            valuePropName: 'checked',
            // rules: [],
          })(<Switch checkedChildren={formatMessage({ id: 'app.base.is-enable.true' })} unCheckedChildren={formatMessage({ id: 'app.base.is-enable.close' })} />)}
        </FormItem>
        <DataLang
                dataModalVisible={dataLangModalVisible}
                isUpdate={isUpdate}
                dataFormValues={dataFormValues}
                common={common || {}}
                handleName={handleNameList}
                nameList={nameListLang}
                onSubmit={handleSubmitDataForm}
                onCancel={() => handleDataModalVisible(false)}
            />
    {
      previewModelVisible && (
        <PreviewForm
          previewModelVisible={previewModelVisible}
          onVisibleModel={handlePreviewModalVisible}
          previewImg={previewImg}
        />
      )
    }
  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
